package excmy

import (
	"encoding/csv"
	"golang.org/x/text/encoding/simplifiedchinese"
	"golang.org/x/text/transform"
	"os"
)

// CSVReadGBK reads a CSV file with GBK encoding and returns a 2D slice of strings.
func CSVReadGBK(filename string) ([][]string, error) {
	file, err := os.Open(filename)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	// Create a reader that converts from GBK to UTF-8.
	decoder := simplifiedchinese.GBK.NewDecoder()
	reader := transform.NewReader(file, decoder)

	// Create a new CSV reader.
	csvReader := csv.NewReader(reader)

	// Read in the CSV records.
	records, err := csvReader.ReadAll()
	if err != nil {
		return nil, err
	}

	// Convert the records to a slice of slices of strings.
	var data [][]string
	for _, record := range records {
		data = append(data, record)
	}

	return data[1:], nil
}

// WriteNEWCSV writes a 2D slice of strings to a CSV file.
func WriteNEWCSV(filename string, data [][]string) error {
	// Create a new CSV file.
	file, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer file.Close()

	// Create a new CSV writer.
	writer := csv.NewWriter(file)

	// Write the records to the CSV file.
	for _, record := range data {
		if err := writer.Write(record); err != nil {
			return err
		}
	}

	// Flush the writer to ensure all records are written to the file.
	writer.Flush()

	// Check for any write error.
	if err := writer.Error(); err != nil {
		return err
	}

	return nil
}
